import { showImagePreview, showSuccessToast } from 'vant'
import { onBeforeUnmount } from 'vue'
import { onMounted } from 'vue'
import { ref } from 'vue'
import { likePost } from '@/api/home'
import type { likePostType } from '@/types/home'
import { patientOrder, patientOrderCancel } from '@/api/user'
import { OrderType } from '@/enums'
import { patientConsultPrescription } from '@/api/room'

// 屏幕宽度
export const useWindowWidth = () => {
  // 屏幕宽度可能变化
  const initWidth = ref(window.innerWidth)
  const resizeEvent = () => {
    console.log('宽度', window.innerWidth)
    initWidth.value = window.innerWidth
  }
  onMounted(() => {
    window.addEventListener('resize', resizeEvent)
  })
  onBeforeUnmount(() => {
    window.removeEventListener('resize', resizeEvent)
  })

  return initWidth
}

// 关注封装抽离
export const useLike = (type: likePostType = 'doc') => {
  // 合理使用规则
  const loading = ref(false)
  // 接口参数传递 参数的类型可以定义的少于实参的数据类型  定义{a:number}    传 {a:number,b:string,......}
  const likeClick = async (i: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await likePost({
        type: type,
        id: i.id
      })
      showSuccessToast(i.likeFlag === 1 ? '取消关注成功' : '关注操作成功')
      // i.likeFlag = (1 - i.likeFlag) as 0 | 1
      i.likeFlag = i.likeFlag === 1 ? 0 : 1
    } finally {
      loading.value = false
    }
  }

  return { loading, likeClick }
}

// 订单的删除
export const delOrder = (id: string, callback?: () => void) => {
  const loading = ref(false)
  const delEvent = async () => {
    loading.value = true
    try {
      await patientOrder(id)
      showSuccessToast('删除成功')
      // 你自行操作余下部分
      callback && callback()
    } finally {
      loading.value = false
    }
  }
  return { loading, delEvent }
}

// 取消订单
export const useCancelOrder = () => {
  const cancelLoading = ref(false)
  const cancelEvent = async (item: { id: string; statusValue: string; status: OrderType }) => {
    cancelLoading.value = true
    try {
      await patientOrderCancel(item.id)
      showSuccessToast('取消订单成功')
      item.statusValue = '已取消'
      item.status = OrderType.ConsultCancel
    } finally {
      cancelLoading.value = false
    }
  }
  return { cancelLoading, cancelEvent }
}

// 查看处方
export const useLookEvent = () => {
  // 查看处方
  const lookEvent = async (id: string) => {
    // 拿到处方图片
    const res = await patientConsultPrescription(id)
    showImagePreview([res.data.url])
  }
  return { lookEvent }
}
